<template>
  <div class="icons">
    <swiper v-if="showIcons">
      <swiper-slide v-for="(page ,index) in pages" :key="index">
        <div class="icon" v-for="(item ,index) in page" :key="index">
          <div class="icon-img">
            <img class="icon-imgcontent" :src="item.iconsUrl" />
          </div>
          <p class="icon-desc ellipsis">{{item.name}}</p>
        </div>
      </swiper-slide>
      <!-- Optional controls -->
      <div class="swiper-pagination" slot="pagination"></div>
    </swiper>
  </div>
</template>
<script>
import axios from "axios";
import {mapState} from 'vuex'
export default {
  name: "icons",
  // props:{
  // iconsPosition:Array
  // },
  data() {
    return {
      lastCity:'',
      swiperOption: {
        pagination: ".swiper-pagination",
        loop: true
      },
      iconList: []
    };
  },
  created() {
    this.lastCity = this.city
    // console.log("created")
    this.getIconList();
  },
  computed: {
    ...mapState(['city']), //只能放在计算属性里面 

    //判断获取到的列表数据
    showIcons() {
      return this.pages.length;
    },
    //分页
    pages() {
      const pages = [];
      this.iconList.forEach((item, index) => {
        const page = Math.floor(index / 8);
        if (!pages[page]) {
          pages[page] = [];
        }
        pages[page].push(item);
      });
      return pages;
    }
  },
  methods: {
    getIconList() {
      axios.get("/api/index.json?city1=" + this.city).then((res) => {
        this.iconList = res.data.data.iconList;
      });
    },
  },
    // 增加 <keep-alive></keep-alive> 之后新增的生命周期
  activated(){
    if (this.lastCity !== this.city){
      this.getIconList()
      this.lastCity = this.city
    }
    // console.log("activated")
  }
};
</script>
<style scoped>
.icons >>> .swiper-container {
  height: 0;
  padding-bottom: 50%;
}
.icons {
  overflow: hidden;
  width: 100%;
  padding-bottom: 3%;
}
.icons .icon {
  position: relative;
  overflow: hidden;
  float: left;
  width: 25%;
  height: 0;
  padding-bottom: 25%;
}
.icons .icon .icon-img {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 22px;
  box-sizing: border-box;
  padding: 5px;
}
.icons .icon .icon-img .icon-imgcontent {
  height: 100%;
  display: block;
  margin: 0 auto;
}
.icons .icon .icon-desc {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  height: 22px;
  line-height: 22px;
  text-align: center;
  color: #333;
  /* 出现。。。的效果
    overflow:hidden;
    white-space:nowrap;
    text-overflow:ellipsis */
}
</style>